package cn.wsn2018.tools.util;


import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadUtil {


    //线程池
    static volatile private ThreadPoolExecutor threadPoolExecutor;
    public static  ThreadPoolExecutor getThreadPoolExecutor(){
        /**
         * 单例模式
         * */
        if (threadPoolExecutor==null){
            synchronized (ThreadPoolExecutor.class){
                if (threadPoolExecutor==null){
                    //创建拒绝策略  ---让调用线程来处理这个任务
                    ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
                    //创建线程池 最多三种文件同时执行
                    threadPoolExecutor=new ThreadPoolExecutor(3,
                            10,
                            0L,
                            TimeUnit.MILLISECONDS,
                            new LinkedBlockingQueue<Runnable>(),
                            callerRunsPolicy);
                }
            }
        }
        return  threadPoolExecutor;
    }


    // 用threadlcoal来存储用户的请求-记录用户名
   static volatile private ThreadLocal<String> userName;
   public static ThreadLocal<String> getThreadLocalUserName(){
       /**
        * 单例模式
        * */
       if (userName==null){
           synchronized (ThreadLocal.class){
               if (userName==null){
                   userName=new ThreadLocal<String> ();
               }
           }
       }
       return userName;
   }

   //休眠函数
    static void sleep(long seconds){
        try {
            Thread.sleep(seconds*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
